package service

import (
	"fmt"
	"go-kit-service/pkg/logger"
	"os"

	"go.uber.org/zap"
)

const (
	VideoDir = "./videos"
)

type VideoService struct {
	stopSignal chan os.Signal
}

type VideoInfo struct {
	Name string
	Size int64
}

// 检查一下视频文件夹是否存在，不存在就创建一个
func checkVideoDir() {
	_, err := os.Stat(VideoDir)
	if err != nil {
		logger.Error("get VideoDir state info", zap.Error(err))
		if mkErr := os.Mkdir(VideoDir, 0777); mkErr != nil {
			logger.Panic("create VideoDir", zap.Error(mkErr), zap.String("VideoDir", VideoDir))
		}
		return
	}
}

func NewService() *VideoService {
	checkVideoDir()

	return &VideoService{
		stopSignal: make(chan os.Signal, 1),
	}
}

func (service *VideoService) VideoList() []VideoInfo {
	var fileList = []VideoInfo{}

	dir, err := os.ReadDir(VideoDir)
	if err != nil {
		return fileList
	}

	for _, file := range dir {
		fileName := file.Name()
		filePath := VideoDir + "/" + fileName

		fileInfo, err := os.Stat(filePath)
		if err != nil {
			logger.Error("get video file info", zap.Error(err), zap.String("filePath", filePath))
			continue
		}

		fileList = append(fileList, VideoInfo{
			Name: fileName,
			Size: fileInfo.Size(),
		})
	}

	return fileList
}

func (service *VideoService) UploadVideo(name string, videoData []byte) error {
	filePath := VideoDir + "/" + name
	_, err := os.Stat(filePath)
	if err == nil {
		logger.Error("upload fileName has exist")
		return fmt.Errorf("upload fileName has exist")
	}

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0777)
	if err != nil {
		logger.Error("open filePath", zap.Error(err), zap.String("filePath", filePath))
		return fmt.Errorf("open filePath: %s, error: %v", filePath, err)
	}
	defer file.Close()

	_, err = file.Write(videoData)
	if err != nil {
		logger.Error("upload video file write to file", zap.Error(err))
		return fmt.Errorf("upload video file write to file, error: %v", err)
	}

	return nil
}

func (service *VideoService) DownloadVideo(videName string) ([]byte, error) {
	filepath := VideoDir + "/" + videName
	_, err := os.Stat(filepath)
	if err != nil {
		logger.Error("need download video", zap.Error(err), zap.String("filepath", filepath))
		return []byte{}, fmt.Errorf("download videl file error: %v", err)
	}

	fileSrc, err := os.ReadFile(filepath)
	if err != nil {
		logger.Error("read video file src", zap.Error(err), zap.String("filepath", filepath))
		return []byte{}, fmt.Errorf("read video file error: %v", err)
	}

	return fileSrc, nil
}

func (service *VideoService) ConvertVideo(video []byte) ([]byte, error) {
	return video, nil
}
